<script setup lang="ts">
import {getConsultOrderPre,getConsultOrderId} from '@/services/consult'
import {getPatientInformation} from '@/services/user'
import {ref,onMounted} from 'vue'
import type {ConsultOrderPreData,PartialConsult} from '@/types/consult'
import type {Patient} from '@/types/user'
import {useConsultStore} from '@/stores/consult'
import { showToast,showConfirmDialog ,showDialog   } from 'vant'
import { useRouter,onBeforeRouteLeave } from 'vue-router'
// 存放支付信息
const payInfo=ref<ConsultOrderPreData>()
const store=useConsultStore()
// 获取支付信息
const loadPayInfo=async ()=>{
  const res=await getConsultOrderPre({
    type:store.consult.type,
    illnessType:store.consult.illnessType
  })
  payInfo.value=res.data
  // 设置优惠券
  store.setCoupon(payInfo.value.couponId)
}
// 存放患者信息
const PatientInfo=ref<Patient>()
// 获取患者信息
const getPatientInfo=async ()=>{
  if (!store.consult.patientId) return
  const res= await getPatientInformation(store.consult.patientId)
  PatientInfo.value=res.data
  
}
onMounted(()=>{
  type Key = keyof PartialConsult
  const validKeys :Key[]=[
    'type',
    'illnessType',
    'depId',
    'illnessDesc',
    'illnessTime',
    'consultFlag',
    'patientId'
  ]
  const valid=validKeys.every(key => store.consult[key] !==undefined)
  if (!valid) {
    return showDialog({
      title: '温馨提示',
      message: '支付信息不完整请重新填写，如果未支付可以去记录继续支付',
      confirmButtonColor:'red'
    }).then(() => {
      // on close
      router.push('/')
    });
  }
  loadPayInfo()
  getPatientInfo()
}
)
// 是否显示选择支付
const show=ref(false)
// 勾选支付协议
const agree=ref(false)
// 微信和支付宝支付
const paymentMethod=ref<0 | 1>()
// 订单ID
const orderId=ref<string>()
// 按钮loading
const loading=ref(false)
const submit=async ()=>{
  if (!agree.value) return showToast('请勾选支付协议')
  loading.value=true
  show.value=true
  const res=await getConsultOrderId(store.consult)
  orderId.value=res.data.id
  loading.value=false
  store.clear()
}
const router=useRouter()
// 关闭
const close=()=>{
  showConfirmDialog({
  title: '关闭支付',
  message:'取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
  cancelButtonText:'仍要关闭',
  confirmButtonText:'继续支付'
})
  .then(() => {
    // on confirm
    return false
  })
  .catch(() => {
    // on cancel
    orderId.value=''
    router.push('/user/consult')
    return true
  });
}

onBeforeRouteLeave(()=>{
  if (orderId.value) return false
})
// const pay=async ()=>{
//   if (paymentMethod.value===undefined) return showToast('请选择支付方式')
//   showLoadingToast({
//     message: '跳转支付...',
//     forbidClick: true,
//   })
//   if (orderId.value) {
//     const res=await getConsultOrderPayUrl({
//       paymentMethod:paymentMethod.value,
//       orderId:orderId.value,
//       payCallback:'http://localhost:5173/room'
//     })
//     console.log(res);
//     location.href=res.data.payUrl
//   }
// }
</script>

<template>
  <div class="consult-pay-page" v-if="PatientInfo && payInfo">
    <cp-nav-bar title="支付" />
    <div class="pay-info">
      <p class="tit">图文问诊 {{payInfo.payment}} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <van-cell-group>
      <van-cell title="优惠券" :value="`-¥${payInfo.couponDeduction}`" />
      <van-cell title="积分抵扣" :value="`-¥${payInfo.pointDeduction}`" />
      <van-cell title="实付款" :value="`¥${payInfo.actualPayment}`" class="pay-price" />
    </van-cell-group>
    <div class="pay-space"></div>
    <van-cell-group>
      <van-cell title="患者信息" :value="`${ PatientInfo.name } | ${PatientInfo.genderValue} | ${PatientInfo.age}岁`"></van-cell>
      <van-cell title="病情描述" :label="store.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="agree">我已同意 <span class="text">支付协议</span></van-checkbox>
    </div>
    <van-submit-bar :loading="loading" button-type="primary" :price="payInfo.actualPayment * 100" button-text="立即支付" text-align="left" @click="submit" />
  </div>
  <!-- <van-action-sheet v-model:show="show" title="选择支付方式" :close-on-popstate="false" :closeable="false" :before-close="close">
      <div class="pay-type">
        <p class="amount">￥{{ payInfo?.actualPayment.toFixed(2) }}</p>
        <van-cell-group>
          <van-cell title="微信支付" @click="paymentMethod = 0">
            <template #icon><cp-icon name="consult-wechat" /></template>
            <template #extra><van-checkbox :checked="paymentMethod === 0" /></template>
          </van-cell>
          <van-cell title="支付宝支付" @click="paymentMethod = 1">
            <template #icon><cp-icon name="consult-alipay" /></template>
            <template #extra><van-checkbox :checked="paymentMethod === 1" /></template>
          </van-cell>
        </van-cell-group>
        <div class="btn">
          <van-button type="primary" round block @click="pay">立即支付</van-button>
        </div>
      </div>
  </van-action-sheet> -->
    <cp-pay
    pay-callback="http://localhost:5173/room" 
    :actual-payment="payInfo?.actualPayment!" 
    v-model:show='show'
    :order-id="orderId!"
    :close="close"
    ></cp-pay>

</template>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 46px 0 50px 0;
}
.pay-info {
  display: flex;
  padding: 15px;
  flex-wrap: wrap;
  align-items: center;
  .tit {
    width: 100%;
    font-size: 16px;
    margin-bottom: 10px;
  }
  .img {
    margin-right: 10px;
    width: 38px;
    height: 38px;
    border-radius: 4px;
    overflow: hidden;
  }
  .desc {
    flex: 1;
    > span {
      display: block;
      color: var(--cp-tag);
      &:first-child {
        font-size: 16px;
        color: var(--cp-text2);
      }
    }
  }
}
.pay-price {
  ::v-deep() {
    .vam-cell__title {
      font-size: 16px;
    }
    .van-cell__value {
      font-size: 16px;
      color: var(--cp-price);
    }
  }
}
.pay-space {
  height: 12px;
  background-color: var(--cp-bg);
}
.pay-schema {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  .text {
    color: var(--cp-primary);
  }
}
::v-deep() {
  .van-submit-bar__button {
    font-weight: normal;
    width: 160px;
  }
}
.pay-type {
  .amount {
    padding: 20px;
    text-align: center;
    font-size: 16px;
    font-weight: bold;
  }
  .btn {
    padding: 15px;
  }
  .van-cell {
    align-items: center;
    .cp-icon {
      margin-right: 10px;
      font-size: 18px;
    }
    .van-checkbox :deep(.van-checkbox__icon) {
      font-size: 16px;
    }
  }
}

</style>
